package com.yyge.interceptor;

import com.yyge.dto.ResultCode;
import com.yyge.exception.ApplicationException;
import com.yyge.util.TokenUtil;
import com.yyge.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenUtil tokenUtil;

    /*拦截器 对页面API进行鉴权 鉴权拦截器*/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("--------鉴权拦截器 执行了:" + request.getServletPath());
        //System.out.println("handler:" + handler);
        String header = request.getHeader("Authorization");
        if(header == null){
            //直接抛异常即可 因为会被异常类拦截
           throw new ApplicationException(ResultCode.SYSTEM_NEED_TOKEN);
        }

        LoginVO vo=tokenUtil.getLoginVO(header);

        if (vo==null) {
            throw new ApplicationException(ResultCode.SYSTEM_CODE_INVALID);
        }

        /*保存用户信息*/
        tokenUtil.loginVOThreadLocal.set(vo);

        //放行
        return true;
    }
}